package com.shenyue.nbtownlet.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.google.android.flexbox.FlexboxLayout;
import com.hitomi.glideloader.GlideImageLoader;
import com.hitomi.tilibrary.style.progress.ProgressPieIndicator;
import com.hitomi.tilibrary.transfer.TransferConfig;
import com.hitomi.tilibrary.transfer.Transferee;
import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.adapter.CheckWorkDetailViewAdapter;
import com.shenyue.nbtownlet.adapter.LabelListViewAdapter;
import com.shenyue.nbtownlet.base.BaseActivity;
import com.shenyue.nbtownlet.databinding.ActivityCheckWorkDetailBinding;
import com.shenyue.nbtownlet.databinding.CheckWorkSheetDialogBinding;
import com.shenyue.nbtownlet.databinding.ImagePartItemRemoveBinding;
import com.shenyue.nbtownlet.event.BaseListener;
import com.shenyue.nbtownlet.model.AppInsertTaskModel;
import com.shenyue.nbtownlet.model.AppLoginModel;
import com.shenyue.nbtownlet.model.AppMonthlyModel;
import com.shenyue.nbtownlet.model.DefaultModel;
import com.shenyue.nbtownlet.model.FileUploadModel;
import com.shenyue.nbtownlet.ui.Wait;
import com.shenyue.nbtownlet.util.DensityUtil;
import com.shenyue.nbtownlet.util.GlideUtil;
import com.shenyue.nbtownlet.util.NetWorkUtils;
import com.shenyue.nbtownlet.util.StringUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class CheckWorkDetailActivity extends BaseActivity implements View.OnClickListener,
        CheckWorkDetailViewAdapter.CheckWorkDetailListItemClickListener,
        AdapterView.OnItemClickListener,
        BaseListener {
    private ActivityCheckWorkDetailBinding binding;
    private Context mContext;
    private Handler mHandler = new Handler();
    private String mainId;
    private CheckWorkSheetDialogBinding sheetDialogBinding;
    private BottomSheetDialog sheetDialog;
    private CheckWorkDetailViewAdapter listViewAdapter;
    private LabelListViewAdapter aAdapter, bAdapter, cAdapter;
    private JSONArray methodJSON;
    private String areaId, areaName, year, month;
    private boolean isLoading = false;
    private JSONObject mainJson;
    private int[] wh;
    private List<String> addImages = new ArrayList<>();
    private List<ImageView> addImageViews = new ArrayList<>();
    private Transferee transferee;
    private static final int REQUEST_CODE_SELECT = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_check_work_detail);
        mContext = this;
        transferee = Transferee.getDefault(mContext);

        Bundle bundle = getIntent().getExtras();
        mainId = bundle.getString(DefaultModel.PAGE_DATA_ID);
        areaId = bundle.getString("areaId");
        areaName = bundle.getString("areaName");
        year = bundle.getString("year");
        month = bundle.getString("month");

        setActionBar(true, areaName + year + "年" + month + "月考核");

        binding.btnAdd.setOnClickListener(this);

        sheetDialogBinding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.check_work_sheet_dialog, null, false);
        sheetDialogBinding.btnCancel.setOnClickListener(new SendClickListener());
        sheetDialogBinding.btnSubmit.setOnClickListener(new SendClickListener());
        sheetDialog = new BottomSheetDialog(this);
        sheetDialog.setContentView(sheetDialogBinding.getRoot());
        sheetDialog.setCancelable(false);
        sheetDialog.setCanceledOnTouchOutside(false);
        BottomSheetBehavior mDialogBehavior = BottomSheetBehavior.from((View) sheetDialogBinding.getRoot().getParent());
        if (mDialogBehavior != null) {
            mDialogBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            mDialogBehavior.setPeekHeight(DensityUtil.dip2px(mContext, 1000));
        }

        listViewAdapter = new CheckWorkDetailViewAdapter(mContext);
        binding.listView.setAdapter(listViewAdapter);
        listViewAdapter.setOnItemClickListener(this);

        binding.ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if (!NetWorkUtils.isNetworkConnected(mContext)) {
                    binding.ptrClassicFrameLayout.refreshComplete();
                    showMsg(getString(R.string.no_network));
                    return;
                }
                if (mainId == null || isLoading) {
                    binding.ptrClassicFrameLayout.refreshComplete();
                    return;
                }
                queryContnets(mainId);
            }
        });

        binding.ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                if (!NetWorkUtils.isNetworkConnected(mContext)) {
                    binding.ptrClassicFrameLayout.loadMoreComplete(false);
                    showMsg(getString(R.string.no_network));
                    return;
                }
            }
        });
        binding.ptrClassicFrameLayout.disableWhenHorizontalMove(true);

        sheetDialogBinding.iAssessmentPart.setOnClickListener(this);
        sheetDialogBinding.iiAssessmentPart.setOnClickListener(this);
        sheetDialogBinding.iiiAssessmentPart.setOnClickListener(this);
        sheetDialogBinding.iAssessment.setParentScrollView(sheetDialogBinding.scrollView);
        sheetDialogBinding.iiAssessment.setParentScrollView(sheetDialogBinding.scrollView);
        sheetDialogBinding.iiiAssessment.setParentScrollView(sheetDialogBinding.scrollView);
        setAssessment();

        wh = DensityUtil.getWH(this, 2, 30);
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(wh[0], wh[1]);
        sheetDialogBinding.btnPhoto.setLayoutParams(layoutParams);
        sheetDialogBinding.btnPhoto.setOnClickListener(this);

        if (mainId != null) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    binding.ptrClassicFrameLayout.autoRefresh();
                    queryMain(mainId);
                }
            }, 32);
        }
    }

    /**
     * 获取主表信息
     *
     * @param mainId
     */
    private void queryMain(String mainId) {
        JSONObject param = new JSONObject();
        param.put("id", mainId);
        AppMonthlyModel.GetAssessInfo(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                JSONObject item = JSON.parseObject(val);
                mainJson = item;
                areaId = StringUtil.dTs(item.getString("AREAID"));
                binding.OPINION.setText(item.getString("OPINION"));
                binding.REMARK.setText(item.getString("REMARK"));
            }

            @Override
            public void error(String error, String action) {

            }
        });
    }

    /**
     * 获取列表内容
     *
     * @param mainId
     */
    private void queryContnets(String mainId) {
        listViewAdapter.clear();
        JSONObject param = new JSONObject();
        param.put("mainid", mainId);
        AppMonthlyModel.GetContentsByMainId(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                isLoading = true;
                binding.ptrClassicFrameLayout.refreshComplete();
                binding.ptrClassicFrameLayout.setLoadMoreEnable(false);
                JSONArray items = JSON.parseArray(val);
                listViewAdapter.addItems(items);
            }

            @Override
            public void error(String error, String action) {
                isLoading = false;
                binding.ptrClassicFrameLayout.refreshComplete();
                binding.ptrClassicFrameLayout.setLoadMoreEnable(false);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (transferee != null)
            transferee.destroy();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == binding.btnAdd.getId()) {
            //清理数据
            clearData();
            queryIAssessmentList();
            sheetDialog.show();
            return;
        }
        switch (view.getId()) {
            case R.id.i_assessment_part: {//考核分类
                changeVisibility(sheetDialogBinding.iAssessment, getImageView((LinearLayout) view));
                break;
            }
            case R.id.ii_assessment_part: {//整治任务
                changeVisibility(sheetDialogBinding.iiAssessment, getImageView((LinearLayout) view));
                break;
            }
            case R.id.iii_assessment_part: {//考核要求
                changeVisibility(sheetDialogBinding.iiiAssessment, getImageView((LinearLayout) view));
                break;
            }
            case R.id.btn_photo: {
                doPhoto();
                break;
            }
        }
    }

    private void doPhoto() {
        MultiImageSelector.create()
                .showCamera(true) // show camera or not. true by default
                .count(9) // max select image size, 9 by default. used width #.multi()
                .multi() // multi mode, default mode;
                .start(this, REQUEST_CODE_SELECT);
    }

    @Override
    public void onItemClick(int position) {
        if (!NetWorkUtils.isNetworkConnected(mContext)) {
            showMsg(getString(R.string.no_network));
            return;
        }
        //点击展现明细
        clearData();
        JSONObject content = (JSONObject) listViewAdapter.getItem(position);
        showDetail(content, position);
    }

    @Override
    public void onItemDelClick(final int position) {
        if (!NetWorkUtils.isNetworkConnected(mContext)) {
            showMsg(getString(R.string.no_network));
            return;
        }
        final JSONObject item = (JSONObject) listViewAdapter.getItem(position);
        if (StringUtil.isNull(item.getString("ID")) || item.getString("ID").startsWith("T")) {
            listViewAdapter.removeItem(position);
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("温馨提示")
                .setMessage("确认删除？")
                .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        Wait.sharedInstance().start(mContext);
                        JSONObject param = new JSONObject();
                        param.put("id", StringUtil.dTs(item.getString("ID")));
                        AppMonthlyModel.DeleteContent(mContext, param, new BaseListener() {
                            @Override
                            public void success(String val, String action) {
                                listViewAdapter.removeItem(position);
                                Wait.sharedInstance().stop();
                            }

                            @Override
                            public void error(String error, String action) {
                                Wait.sharedInstance().stop();
                            }
                        });
                    }
                }).setNegativeButton("取消", null);
        builder.create().show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.submit_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (!NetWorkUtils.isNetworkConnected(this)) {
            showMsg(getString(R.string.no_network));
            return false;
        }
        switch (item.getItemId()) {
            case R.id.action_submit:
                onSave();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent == sheetDialogBinding.iAssessment) {
            JSONArray list = aAdapter.getItems();
            for (int i = 0, j = list.size(); i < j; i++) {
                JSONObject item = (JSONObject) list.get(i);
                item.put("selected", false);
            }
            final JSONObject item = (JSONObject) list.get(position);
            item.put("selected", true);
            aAdapter.notifyDataSetChanged();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    TextView tv = (TextView) sheetDialogBinding.iAssessmentPart.getChildAt(0);
                    tv.setText(item.getString("Name"));
                    tv = (TextView) sheetDialogBinding.iiAssessmentPart.getChildAt(0);
                    tv.setText("考核任务");
                    tv = (TextView) sheetDialogBinding.iiiAssessmentPart.getChildAt(0);
                    tv.setText("考核方法");
                    changeVisibility(sheetDialogBinding.iAssessment, (ImageView) sheetDialogBinding.iAssessmentPart.getChildAt(1));
                }
            }, 32);
            queryIIAssessmentList(StringUtil.dTs(item.getString("ID")));
        } else if (parent == sheetDialogBinding.iiAssessment) {
            JSONArray list = bAdapter.getItems();
            for (int i = 0, j = list.size(); i < j; i++) {
                JSONObject item = (JSONObject) list.get(i);
                item.put("selected", false);
            }
            final JSONObject item = (JSONObject) list.get(position);
            item.put("selected", true);
            bAdapter.notifyDataSetChanged();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    TextView tv = (TextView) sheetDialogBinding.iiAssessmentPart.getChildAt(0);
                    tv.setText(item.getString("Name"));
                    tv = (TextView) sheetDialogBinding.iiiAssessmentPart.getChildAt(0);
                    tv.setText("考核方法");
                    changeVisibility(sheetDialogBinding.iiAssessment, (ImageView) sheetDialogBinding.iiAssessmentPart.getChildAt(1));
                }
            }, 32);
            queryIIIAssessmentList(StringUtil.dTs(item.getString("ID")));
            GetAssessMent(StringUtil.dTs(item.getString("ID")));
        } else if (parent == sheetDialogBinding.iiiAssessment) {
            JSONArray list = cAdapter.getItems();
            for (int i = 0, j = list.size(); i < j; i++) {
                JSONObject item = (JSONObject) list.get(i);
                item.put("selected", false);
            }
            final JSONObject item = (JSONObject) list.get(position);
            item.put("selected", true);
            cAdapter.notifyDataSetChanged();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    TextView tv = (TextView) sheetDialogBinding.iiiAssessmentPart.getChildAt(0);
                    tv.setText(StringUtil.getShortValue(item.getString("REQUIREMENT"), null));
                    changeVisibility(sheetDialogBinding.iiiAssessment, (ImageView) sheetDialogBinding.iiiAssessmentPart.getChildAt(1));
                }
            }, 32);

            if (methodJSON == null)
                return;
            JSONObject dJson = getMethod(StringUtil.dTs(item.getString("ID")));
            if (dJson == null)
                return;
            sheetDialogBinding.REQUIREMENT.setText(dJson.getString("REQUIREMENT"));
            sheetDialogBinding.SCORE.setText(dJson.getString("SCORE"));
            sheetDialogBinding.STANDARD.setText(dJson.getString("STANDARD"));
            sheetDialogBinding.METHOD.setText(dJson.getString("METHOD"));
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null && requestCode == REQUEST_CODE_SELECT) {
            List<String> images = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            for (int i = 0, j = images.size(); i < j; i++) {
                String item = images.get(i);
                if (!this.addImages.contains(item))
                    this.addImages.add(item);
            }
            resetPhotos();
        }
    }

    private class SendClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_cancel: {//取消
                    sheetDialog.hide();
                    break;
                }
                case R.id.btn_submit: {//提交
                    JSONObject content = getContent();
                    if (content == null)
                        return;
                    if (StringUtil.isNull(content.getString("ID"))) {
                        listViewAdapter.addItem(content);
                    } else if (content.getString("ID").startsWith("T")) {
                        String p = content.getString("ID").replace("T", "");
                        listViewAdapter.removeItem(Integer.valueOf(p));
                        listViewAdapter.addItem(content, Integer.valueOf(p));
                    } else {
                        listViewAdapter.updateItem(content);
                    }
                    sheetDialog.hide();
                    break;
                }
            }
        }
    }

    //=====================
    private JSONObject getContent() {
        String s = sheetDialogBinding.btnSubmit.getTag().toString();
        JSONObject content = new JSONObject();
        if (StringUtil.isNull(s) || s.startsWith("T")) {
            content.put("ID", s);
            content.put("CREATORID", AppLoginModel.getIdentityId(mContext));// 创建人的身份ID
            content.put("CREATORNAME", AppLoginModel.getUserName(mContext));// 创建人的名字
        } else
            content.putAll(JSON.parseObject(s));
        content.put("FILEID", StringUtil.join(JSON.parseArray(JSON.toJSONString(addImages))));//   上传的问题图片上传后的地址
        content.put("SCORE", sheetDialogBinding.SCORE.getText().toString().trim());//问题选择完毕后，默认为第三级的考核方法的分数，可修改
        content.put("EDITID", AppLoginModel.getIdentityId(mContext));//  编辑人的身份ID
        content.put("EDITNAME", AppLoginModel.getUserName(mContext));//   编辑人的名字
        content.put("OPINION", sheetDialogBinding.OPINION.getText().toString().trim());//   考核意见
        content.put("EDITTIME", "/Date(" + new Date().getTime() + ")/");
        String ASSESSTYPEID = aAdapter.getSelectItemId();
        if (StringUtil.isNull(ASSESSTYPEID)) {
            Toast.makeText(mContext, "请选择考核分类", Toast.LENGTH_SHORT).show();
            return null;
        }
        String ASSESSTASKID = bAdapter.getSelectItemId();
        if (StringUtil.isNull(ASSESSTASKID)) {
            Toast.makeText(mContext, "请选择考核任务", Toast.LENGTH_SHORT).show();
            return null;
        }
        String ASSESSMENTID = cAdapter.getSelectItemId();
        if (StringUtil.isNull(ASSESSMENTID)) {
            Toast.makeText(mContext, "请选择考核方法", Toast.LENGTH_SHORT).show();
            return null;
        }

        content.put("ASSESSMENTASKID", ASSESSTASKID);//    问题种类的考核任务ID
        content.put("ASSESSMENTTYPEID", ASSESSTYPEID);//   问题种类的考核分类ID
        content.put("ASSESSMENTID", ASSESSMENTID);//    问题种类的考核方法ID
        content.put("ASSESSMENT_NAME", cAdapter.getSelectItem().getString("REQUIREMENT"));

        content.put("$type$", "v");

        return content;
    }

    private void GetAssessMent(final String id) {
        JSONObject param = new JSONObject();
        param.put("taskid", id);
        AppMonthlyModel.GetAssessMent(mContext, param, new BaseListener() {

            @Override
            public void success(String val, String action) {
                methodJSON = JSON.parseArray(val);
            }

            @Override
            public void error(String error, String action) {

            }
        });
    }

    private JSONObject getMethod(String id) {
        for (int i = 0, j = methodJSON.size(); i < j; i++) {
            JSONObject item = methodJSON.getJSONObject(i);
            if (id.equals(StringUtil.dTs(item.getString("ID"))))
                return item;
        }
        return null;
    }

    private void setAssessment() {
        aAdapter = new LabelListViewAdapter(mContext);
        sheetDialogBinding.iAssessment.setAdapter(aAdapter);
        sheetDialogBinding.iAssessment.setOnItemClickListener(this);

        bAdapter = new LabelListViewAdapter(mContext);
        sheetDialogBinding.iiAssessment.setAdapter(bAdapter);
        sheetDialogBinding.iiAssessment.setOnItemClickListener(this);

        cAdapter = new LabelListViewAdapter(mContext);
        sheetDialogBinding.iiiAssessment.setAdapter(cAdapter);
        sheetDialogBinding.iiiAssessment.setOnItemClickListener(this);
    }

    private void queryIAssessmentList() {
        AppInsertTaskModel.GetAssessType(mContext, null, new BaseListener() {
            @Override
            public void success(String val, String action) {
                aAdapter.clear();
                aAdapter.addItems(JSON.parseArray(val));
            }

            @Override
            public void error(String error, String action) {

            }
        });
    }

    private void queryIIAssessmentList(final String id) {
        JSONObject param = new JSONObject();
        param.put("type", id);
        AppInsertTaskModel.GetAssessTaskByType(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                bAdapter.clear();
                bAdapter.addItems(JSON.parseArray(val));
            }

            @Override
            public void error(String error, String action) {

            }
        });
    }

    private void queryIIIAssessmentList(final String id) {
        JSONObject param = new JSONObject();
        param.put("id", id);
        AppInsertTaskModel.GetAssessMentBYTaskID(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                cAdapter.clear();
                cAdapter.addItems(JSON.parseArray(val));
            }

            @Override
            public void error(String error, String action) {

            }
        });
    }

    private ImageView getImageView(LinearLayout view) {
        return (ImageView) view.getChildAt(1);
    }

    private void changeVisibility(View view, ImageView arrow) {
        int i = view.getVisibility();
        if (i == View.GONE) {
            view.setVisibility(View.VISIBLE);
            arrow.setImageResource(R.mipmap.arrow_up);
        } else {
            view.setVisibility(View.GONE);
            arrow.setImageResource(R.mipmap.arrow_down);
        }
    }

    /**
     * 展现明细
     *
     * @param content
     */
    private void showDetail(JSONObject content, int position) {
        if (StringUtil.isNull(content.getString("ID"))) {
            sheetDialogBinding.btnSubmit.setTag("T" + position);
            setDetail(content);
        } else {
            sheetDialogBinding.btnSubmit.setTag(content.toString());
            if ("v".equals(content.getString("$type$"))) {
                setDetail(content);
            } else {
                GetContentById(content);
            }
        }

        sheetDialogBinding.OPINION.setText(content.getString("OPINION"));
        sheetDialogBinding.SCORE.setText(content.getString("SCORE"));
        sheetDialogBinding.scrollView.scrollTo(0, 0);
        sheetDialog.show();
    }

    private void GetContentById(final JSONObject content) {
        JSONObject param = new JSONObject();
        param.put("id", StringUtil.dTs(content.getString("ID")));
        AppMonthlyModel.GetContentById(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                setDetail(JSON.parseObject(val));
            }

            @Override
            public void error(String error, String action) {

            }
        });
    }

    private void setDetail(final JSONObject content) {
        final String A = StringUtil.dTs(content.getString("ASSESSMENTTYPEID"));//   问题种类的考核分类ID
        final String B = StringUtil.dTs(content.getString("ASSESSMENTASKID"));//问题种类的考核任务ID
        final String C = StringUtil.dTs(content.getString("ASSESSMENTID"));//    问题种类的考核方法ID
        AppInsertTaskModel.GetAssessType(mContext, null, new BaseListener() {
            @Override
            public void success(String val, String action) {
                aAdapter.clear();
                JSONArray items = JSON.parseArray(val);
                for (int i = 0, j = items.size(); i < j; i++) {
                    JSONObject item = (JSONObject) items.get(i);
                    if (StringUtil.dTs(item.getString("ID")).equals(A)) {
                        item.put("selected", true);
                        setA(content, item, B, C);
                    } else
                        item.put("selected", false);
                }
                aAdapter.addItems(items);
            }

            @Override
            public void error(String error, String action) {

            }
        });

        //设置图片
        addImages.clear();
        String FILEID = StringUtil.getValue(content.getString("FILEID"));
        if (!StringUtil.isNull(FILEID) && !"-".equals(FILEID)) {
            String[] array = FILEID.split(",", -1);
            for (String img : array) {
                if(StringUtil.isNull(img))
                    continue;
                addImages.add(img);
            }
        }
        resetPhotos();
    }

    private void setA(final JSONObject content, final JSONObject item, final String B, final String C) {
        TextView tv = (TextView) sheetDialogBinding.iAssessmentPart.getChildAt(0);
        tv.setText(item.getString("Name"));

        JSONObject param = new JSONObject();
        param.put("type", StringUtil.dTs(item.getString("ID")));
        AppInsertTaskModel.GetAssessTaskByType(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                bAdapter.clear();
                JSONArray items = JSON.parseArray(val);
                for (int i = 0, j = items.size(); i < j; i++) {
                    JSONObject item = (JSONObject) items.get(i);
                    if (StringUtil.dTs(item.getString("ID")).equals(B)) {
                        item.put("selected", true);
                        setB(content, item, C);
                    } else
                        item.put("selected", false);
                }
                bAdapter.addItems(items);
            }

            @Override
            public void error(String error, String action) {

            }
        });
    }

    private void setB(final JSONObject content, final JSONObject item, final String C) {
        TextView tv = (TextView) sheetDialogBinding.iiAssessmentPart.getChildAt(0);
        tv.setText(item.getString("Name"));

        JSONObject param = new JSONObject();
        param.put("taskid", StringUtil.dTs(item.getString("ID")));
        AppMonthlyModel.GetAssessMent(mContext, param, new BaseListener() {

            @Override
            public void success(String val, String action) {
                methodJSON = JSON.parseArray(val);
                JSONObject dJson = getMethod(C);
                sheetDialogBinding.REQUIREMENT.setText(dJson.getString("REQUIREMENT"));
                sheetDialogBinding.STANDARD.setText(dJson.getString("STANDARD"));
                sheetDialogBinding.METHOD.setText(dJson.getString("METHOD"));

                JSONObject param = new JSONObject();
                param.put("id", StringUtil.dTs(item.getString("ID")));
                AppInsertTaskModel.GetAssessMentBYTaskID(mContext, param, new BaseListener() {
                    @Override
                    public void success(String val, String action) {
                        cAdapter.clear();
                        JSONArray items = JSON.parseArray(val);
                        for (int i = 0, j = items.size(); i < j; i++) {
                            JSONObject item = (JSONObject) items.get(i);
                            if (StringUtil.dTs(item.getString("ID")).equals(C)) {
                                item.put("selected", true);
                                setC(content, item);
                            } else
                                item.put("selected", false);
                        }
                        cAdapter.addItems(items);
                    }

                    @Override
                    public void error(String error, String action) {

                    }
                });
            }

            @Override
            public void error(String error, String action) {

            }
        });
    }

    private void setC(JSONObject content, JSONObject item) {
        TextView tv = (TextView) sheetDialogBinding.iiiAssessmentPart.getChildAt(0);
        tv.setText(StringUtil.getShortValue(item.getString("REQUIREMENT"), null));
    }

    private void clearData() {
        addImages.clear();
        addImageViews.clear();
        aAdapter.clear();
        bAdapter.clear();
        cAdapter.clear();
        sheetDialogBinding.ASSESSMENTNAME.setText("");
        sheetDialogBinding.ASSESSTASKNAME.setText("");
        sheetDialogBinding.ASSESSTYPENAME.setText("");
        TextView tv = (TextView) sheetDialogBinding.iAssessmentPart.getChildAt(0);
        tv.setText("考核类型");
        tv = (TextView) sheetDialogBinding.iiAssessmentPart.getChildAt(0);
        tv.setText("考核任务");
        tv = (TextView) sheetDialogBinding.iiiAssessmentPart.getChildAt(0);
        tv.setText("考核方法");
        sheetDialogBinding.METHOD.setText("");
        sheetDialogBinding.SCORE.setText("");
        sheetDialogBinding.STANDARD.setText("");
        sheetDialogBinding.REQUIREMENT.setText("");
        sheetDialogBinding.OPINION.setText("");
        sheetDialogBinding.btnSubmit.setTag("");
        resetPhotos();
        sheetDialogBinding.scrollView.scrollTo(0, 0);
    }

    //提交数据时的下标值
    private int itemPosition = 0;
    private boolean submitModify = false;

    private void onSave() {
        if (listViewAdapter.isEmpty()) {
            showToast("请先添加列表考核数据");
            return;
        }
        Wait.sharedInstance().start(mContext);
        //优先处理图片
        for (int i = 0, j = listViewAdapter.getCount(); i < j; i++) {
            JSONObject item = (JSONObject) listViewAdapter.getItem(i);
            String FILEID = StringUtil.getValue(item.getString("FILEID"));
            String[] args = FILEID.split(",", -1);
            JSONArray httpImgs = new JSONArray();
            JSONArray localImgs = new JSONArray();
            for (String img : args) {
                if(StringUtil.isNull(img))
                    continue;
                if (img.startsWith("http://") || img.startsWith("https://"))
                    httpImgs.add(img);
                else
                    localImgs.add(img);
            }
            item.put("httpImgs", httpImgs);
            item.put("localImgs", localImgs);
        }
        //上传图片
        uploadImg(0, 0);
    }

    @Override
    public void success(String val, String action) {
        if (AppMonthlyModel.ADDMONTHLYASSESSMENT_ACTION.equals(action)) {//子列表内容新增接口
            JSONObject rel = JSON.parseObject(val);
            String status = rel.getString("status");
            if ("1".equals(status)) {
                mainId = StringUtil.dTs(rel.getString("id"));
                itemPosition = 0;
                modifyMain(false);
            } else {
                error("数据提交错误，请修改数据再次提交", null);
            }
        } else if (AppMonthlyModel.ADDMONTHLYASSESSMENTCONTENT_ACTION.equals(action)) {//主表信息存在情况下新增及修改子表信息的接口
            JSONObject rel = JSON.parseObject(val);
            String status = rel.getString("status");
            if ("1".equals(status)) {
                JSONObject item = (JSONObject) listViewAdapter.getItem(itemPosition);
                item.put("ID", StringUtil.dTs(rel.getString("id")));
                //继续执行列表数据更新
                itemPosition += 1;
                submitContent();
            } else {
                error("数据提交错误，请修改数据再次提交", null);
            }
        } else if (AppMonthlyModel.SAVEMAIN_ACTION.equals(action)) {//修改主表内容
            JSONObject rel = JSON.parseObject(val);
            String status = rel.getString("status");
            if ("1".equals(status)) {
                //继续执行列表数据更新
                itemPosition += 1;
                if (submitModify)
                    itemPosition = 0;
                submitContent();
            } else {
                error("数据提交错误，请修改数据再次提交", null);
            }
        }
    }

    @Override
    public void error(String error, String action) {
        Wait.sharedInstance().stop();
        showToast(error);
    }

    private void submitContent() {
        if (itemPosition + 1 > listViewAdapter.getCount()) {
            Wait.sharedInstance().stop();
            showToast("数据提交成功");
            setResult(RESULT_OK);
            finish();
        } else {
            JSONObject item = (JSONObject) listViewAdapter.getItem(itemPosition);
            if (StringUtil.isNull(item.getString("ID")) || item.getString("ID").startsWith("T")) {
                item.put("ID", "");
            }
            if (!StringUtil.isNull(item.getString("ASSESSMENTASKID"))) {
                item.put("MONTHLYASSESSMENTID", mainId);
                item.remove("httpImgs");
                item.remove("localImgs");
                AppMonthlyModel.AddMonthlyAssessmentContent(mContext, item, this);
            } else {
                //继续执行列表数据更新
                itemPosition += 1;
                submitContent();
            }
        }
    }

    private void modifyMain(boolean v) {
        submitModify = v;
        JSONObject mainContent = new JSONObject();
        mainContent.put("ID", mainId);//主表ID
        mainContent.put("YEAR", year);//年份
        mainContent.put("MONTH", month);//月份
        mainContent.put("AREAID", areaId);//区域ID
        mainContent.put("CREATORID", mainJson == null ? AppLoginModel.getIdentityId(mContext) : mainJson.getString("CREATORID"));//创建人ID  身份IdentityID
        mainContent.put("CREATORNAME", mainJson == null ? AppLoginModel.getUserName(mContext) : mainJson.getString("CREATORNAME"));// 创建人RealName
        mainContent.put("OPINION", binding.OPINION.getText().toString().trim());//建议
        mainContent.put("REMARK", binding.REMARK.getText().toString().trim());//备注
        mainContent.put("EDITORID", AppLoginModel.getIdentityId(mContext));//编辑人ID  身份IdentityID
        mainContent.put("EDITORNAME", AppLoginModel.getUserName(mContext));//编辑人RealName
        AppMonthlyModel.SaveMain(mContext, mainContent, this);
    }

    private View getImagePartItemRemoveBinding(final String url, int id) {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(wh[0], wh[1]);
        ImagePartItemRemoveBinding root = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.image_part_item_remove, null, false);
        View view = root.getRoot();
        view.setLayoutParams(layoutParams);
        root.btnRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addImages.remove(url);
                resetPhotos();
            }
        });
        root.image.setId(id);
        root.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TransferConfig config = TransferConfig.build()
                        .setNowThumbnailIndex(v.getId())
                        .setSourceImageList(addImages)
                        .setMissPlaceHolder(R.mipmap.ic_empty_photo)
                        .setOriginImageList(addImageViews)
                        .setProgressIndicator(new ProgressPieIndicator())
                        .setImageLoader(GlideImageLoader.with(mContext.getApplicationContext()))
                        .create();
                transferee.apply(config).show(new Transferee.OnTransfereeStateChangeListener() {
                    @Override
                    public void onShow() {
                        Glide.with(mContext).pauseRequests();
                    }

                    @Override
                    public void onDismiss() {
                        Glide.with(mContext).resumeRequests();
                    }
                });
            }
        });
        addImageViews.add(root.image);
        GlideUtil.loadImgCenterCrop(mContext, url, root.image);

        return view;
    }

    private void resetPhotos() {
        addImageViews.clear();
        View btnPhoto = sheetDialogBinding.rectifyImage.getChildAt(sheetDialogBinding.rectifyImage.getChildCount() - 1);
        sheetDialogBinding.rectifyImage.removeAllViews();
        for (int i = 0, j = addImages.size(); i < j; i++) {
            sheetDialogBinding.rectifyImage.addView(getImagePartItemRemoveBinding(addImages.get(i), i));
        }
        sheetDialogBinding.rectifyImage.addView(btnPhoto);
    }

    /**
     * 上传图片
     *
     * @param positionA 数据下标
     * @param positionB 数据图片下标
     */
    private void uploadImg(final int positionA, final int positionB) {
        if (positionA + 1 > listViewAdapter.getCount()) {
            if (StringUtil.isNull(mainId)) {//新建数据
                //子表增加数据
                JSONObject content = (JSONObject) listViewAdapter.getItem(itemPosition);
                content.put("ID", "");
                AppMonthlyModel.AddMonthlyAssessment(mContext, content, this);
            } else {
                modifyMain(true);
            }
            return;
        }
        final JSONObject item = (JSONObject) listViewAdapter.getItem(positionA);
        final JSONArray httpImgs = item.getJSONArray("httpImgs");
        final JSONArray localImgs = item.getJSONArray("localImgs");
        if (localImgs.isEmpty()) {
            uploadImg(positionA + 1, 0);
        } else {
            FileUploadModel.upload(mContext, localImgs.getString(positionB), true, new BaseListener() {
                @Override
                public void success(String val, String action) {
                    JSONObject data = JSON.parseObject(val);
                    httpImgs.add(data.getString("FullUrl"));
                    localImgs.remove(positionB);


                    item.put("FILEID", StringUtil.join(httpImgs) + (localImgs.isEmpty() ? "" : StringUtil.join(localImgs)));

                    uploadImg(positionA, positionB);
                }

                @Override
                public void error(String error, String action) {
                    Wait.sharedInstance().stop();
                    showToast(error);
                }
            });
        }
    }
}
